var StudentList = function () {
	let AUTHORITY=$("#authority").attr("content");
	var initTable=function(){
		// 渲染列表
		var oTable = $("#table").DataTable(
						{
							"bAutoWidth" : true,
//							"bProcessing" : true,
							"bFilter" : true,
							//"bStateSave" : true,
							//"sPaginationType" : "full_numbers",
							"aaSorting" : [ [ 0, 'desc' ] ],
							bSort : false,
							"oLanguage" : { // 汉化
								"sProcessing" : "正在加载数据...",
								"sLengthMenu" : "显示_MENU_条",
								"sZeroRecords" : "没有您要搜索的内容",
								"sInfo" : "从_START_ 到 _END_ 条记录——总记录数为 _TOTAL_ 条",
								"sInfoEmpty" : "记录数为0",
								"sInfoFiltered" : "(全部记录数 _MAX_  条)",
								"sInfoPostFix" : "",
								"sSearch" : "搜索",
								"sUrl" : "",
								"oPaginate" : {
									"sFirst" : "首页",
									"sPrevious" : " 上一页 ",
									"sNext" : " 下一页 ",
									"sLast" : " 末页 "
								}
							},
							"aoColumns" : [
									{
										"mData" : function(source,
												type, val) {
											return source;
										},
										"mRender" : function(value,
												method, row) {
											return '<span class="center"><input type="checkbox" value="'+value.id+'" style="width:18px;height:18px;"></span>'
										}
									},
									{
										"mData" : "stuNo"
									},
									{
										"mData" : "stuName"
									},
									{
										"mData" : "stuSex"
									},
									{
										"mData" : "stuBirth"
									},
									{
										"mData" : "stuGrade"
									},
									{
										"mData" : "stuClass"
									},
									{
										"mData" : "stuJoinTime"
									},
									{
										"mData" : "stuState"
									},
									{																				
										"mData" : function(source,
												type, val) {
											return source;
										},
										"mRender" : function(value,
												method, row) {
											var btn='';
											let view='<a href="/roleview" class="btn green" ><i class="icon-eye-open"></i> 查看</a>';
											let edit='<a class="btn purple role_edit" style="margin-left:10px;" data-id="'+value.id+'" ><i class="icon-edit"></i> 编辑</a>';
											let del='<a class="btn black role_delete" style="margin-left:10px;" data-id="'+value.id+'"><i class="icon-trash"></i> 删除</a>';
											if(AUTHORITY.includes("PERMISSION_ROLE_VIEW")){
												btn+=view;
											}
											if(AUTHORITY.includes("PERMISSION_ROLE_EDIT")){
												btn+=edit;
											}
											if(AUTHORITY.includes("PERMISSION_ROLE_DELETE")){
												btn+=del;
											}
											return btn;
										}
									}],
							bServerSide : true,
							sAjaxSource : "/studentlist",
							fnServerData : function(source, data,
									fnCallBack) {
								// alert("data:"+JSON.stringify(data));
								$.ajax({
									type : "POST",
									dataType : "json",
									url : source,
									data : "param="
											+ JSON.stringify(data),
									// beforeSend:beginWait(),
									success : function(d) {
										if (d.retCode != "1")
											// bootbox.alert(d.retMsg);
											alert(d.retMsg);
										else {
											// $("#total").html(d.retObj.iTotalRecords);
											fnCallBack(d.retObj);
										}
									},
									failure : function(d) {
										// bootbox.alert("服务器无响应");
										alert("服务器无响应");
									},
								// complete:clearWait()
								});
							}
						});
		
		 	jQuery('#table_wrapper .dataTables_filter input').addClass("m-wrap small"); // modify table search input
	        jQuery('#table_wrapper .dataTables_length select').addClass("m-wrap small"); // modify table per page dropdown
	        jQuery('#table_wrapper .dataTables_length select').select2(); // initialzie select2 dropdown

	        $('#table_column_toggler input[type="checkbox"]').change(function(){
	            /* Get the DataTables object again - this is not a recreation, just a get of the object */
//	            var iCol = parseInt($(this).attr("data-column"));
//	            var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
//	            oTable.fnSetColumnVis(iCol, (bVis ? false : true));
	        	
	        	var column = oTable.column( $(this).attr('data-column') );
	            
	            // Toggle the visibility
	            column.visible( ! column.visible() );
	        });
	};
	//表单验证
	var formValid = function () {

	            var form = $('#submit_form');
	            var error = $('.alert-error', form);
	            var success = $('.alert-success', form);
	            
	            form.validate({
	            	debug:true,
	                doNotHideMessage: true, //this option enables to show the error/success messages on tab switch.
	                errorElement: 'span', //default input error message container
	                errorClass: 'validate-inline', // default input error message class
	                focusInvalid: false, // do not focus the last invalid input
	               // onsubmit:true,
	                //onfocusout:true,
	                onfocusout: function(element) {$(element).valid()},
	               // onkeyup:true,
	                onkeyup: function(element) {$(element).valid()},
	               // onclick:true,
	                rules: {
	                    roleName: {
	                        //minlength: 5,
	                        required: true,
	                        remote:"/rolenamecheck"
	                    },
	                    roleCode: {
	                        //minlength: 5,
	                        required: true
	                    }                        
	                },
	                messages: {
	                	roleName: {
		                    required: "角色名不能为空.",
		                    remote:"角色名已存在，请更换！"
		                },
		                roleCode: {
		                    required: "角色码不能为空."
		                }
		            },
	                invalidHandler: function (event, validator) { //display error alert on form submit   
	                    success.hide();
	                    error.show();
	                    //App.scrollTo(error, -200);
	                },

	                highlight: function (element) { // hightlight error inputs
	                    $(element)
	                        .closest('.help-inline').removeClass('ok'); // display OK icon
	                    $(element)
	                        .closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
	                },

	                unhighlight: function (element) { // revert the change dony by hightlight
	                    $(element)
	                        .closest('.control-group').removeClass('error'); // set error class to the control group
	                },

	                success: function (label) {
	                	label.addClass('valid ok') // mark the current input as valid and display OK icon
	                		 .closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
	                },

	                submitHandler: function (form) {
	                    success.show();
	                    error.hide();
	                    //alert("submitted");   
	                    //form.submit();
	                    //add here some ajax code to submit your form or just call form.submit() if you want to submit the form without ajax
	                }

	            });          
	};
	var event=function(){
		//1.删除
		$("#table").on("click", "td a.role_delete", function() {
			var roleId=$(this).attr("data-id");
			layer.confirm('您确定要删除吗，删除后不可恢复？', {
				title:'删除角色',
				btn : [ '是', '否' ]
				,btnAlign: 'c'
			// 按钮
			}, function() {
				deleteRole(roleId);
				//layer.alert("删除了，ID为："+roleId);
			}, function() {
				layer.msg('取消删除！', {
					icon : 2
				});
				// layer.msg('也可以这样', {
				// time: 20000, //20s后自动关闭
				// btn: ['明白了', '知道了']
				// });
			});
		});
		//2.编辑
		$("#table").on("click", "td a.role_edit", function() {
			var roleId=$(this).attr("data-id");
			//layer.msg("编辑ID："+roleId);
			
			layer.open({
				title:'添加角色',
				btn : [ '是', '否' ],
			  type: 1,
			  skin: 'layui-layer-rim', //加上边框
//			  area: ['620px', 'auto'], //宽高
			  area:"40%",
			  content:$('#tab2'),
			  yes:function(index,layerno) {
				  if (!$("#submit_form").valid()) {
				        return;
				     }
					var treeObj = $.fn.zTree.getZTreeObj("treeEdit"), nodes = treeObj.getCheckedNodes(true);
					
					let ids=nodes.map(function(node){
						return node.id;
					});
					
					var unindexed_array = $("#submit_form").serializeArray();
				    var indexed_array = {};

				    $.map(unindexed_array, function(n, i){
				        indexed_array[n['name']] = n['value'];
				    });
					
				    indexed_array.resIds=ids;
				    //layer.alert(JSON.stringify(indexed_array));
					submitForm(JSON.stringify(indexed_array));
					
				},
				btn2 : function(index,
						layerno) {
					layer.msg("取消了",{icon:2});
				}
			});
				
		});

		//2.添加
		$("#btn_add").click(function(){
			//页面层
			layer.open({
				title:'添加角色',
				btn : [ '是', '否' ],
			  type: 1,
			  skin: 'layui-layer-rim', //加上边框
//			  area: ['620px', 'auto'], //宽高
			  area:"40%",
			  content:$('#tab1'),
			  yes:function(index,layerno) {
				  if (!$("#submit_form").valid()) {
				        return;
				     }
					var treeObj = $.fn.zTree.getZTreeObj("treeDemo"), nodes = treeObj.getCheckedNodes(true);
					
					let ids=nodes.map(function(node){
						return node.id;
					});
					
					var unindexed_array = $("#submit_form").serializeArray();
				    var indexed_array = {};

				    $.map(unindexed_array, function(n, i){
				        indexed_array[n['name']] = n['value'];
				    });
					
				    indexed_array.resIds=ids;
				    //layer.alert(JSON.stringify(indexed_array));
					submitForm(JSON.stringify(indexed_array));
					
				},
				btn2 : function(index,
						layerno) {
					layer.msg("取消了",{icon:2});
				}
			});
		});
	};
	function deleteRole(roleId){
		$.ajax(
				{
					type : "POST",
					dataType : "json",
					url : "/roledelete/"+roleId,
//					contentType: "application/json;charset=utf-8",
//					data : "roleId="+roleId
					//,beforeSend : beginWait("研判报告导出中，请稍稍后。。。")
					//,complete : clearWait()
				})
		.done(function(data) {
			if(data&&data.retCode==1){
				layer.msg("恭喜您，删除成功！",{icon:1});
				setTimeout("window.location.reload();", 800)
				
			}else{
				var s=layer.msg("对不起，删除失败！",{icon:2});
				layer.close(s);
			}
			
					
			})
		.fail(function(d) {
			layer.msg("服务器无响应",{icon:2});

		});
	}
	/**
	 * 提交表单
	 * @param data
	 */
	function submitForm(data){
    	$.ajax(
				{
					type : "POST",
					dataType : "json",
					url : "/roleaddsave",
					contentType: "application/json;charset=utf-8",
					data : data
					//,beforeSend : beginWait("研判报告导出中，请稍稍后。。。")
					//,complete : clearWait()
				})
		.done(function(data) {
			if(data&&data.retCode==1){
				var l=layer.msg("恭喜您，添加成功！",{icon:1});
				setTimeout("layer.closeAll();window.location.reload();", 1000)
				
			}else{
				var s=layer.msg("对不起，添加失败！",{icon:3});
				layer.close(s);
			}
			
					
			})
		.fail(function(d) {
			layer.msg("服务器无响应");

		});
	}
	//树控件
    var initZtree=function(){
    	var setting = {
    			view: {
    				showIcon: false
    			},
    			check: {
    				enable: true
    				//,chkboxType: { "Y": "p", "Y": "s" } 
    			},
    			data: {
    				simpleData: {
    					enable: true
    				}
    			}
    		};
    	//添加的Tree
    	$.ajax({
					type : "GET",
					dataType : "json",
					url : "/getAllTreeData"
					//,data : "pids="+ vals
					//,beforeSend : beginWait("研判报告导出中，请稍稍后。。。")
					//,complete : clearWait()
				})
		.done(function(data) {
			$.fn.zTree.init($("#treeDemo"), setting, data);	
					
			})
		.fail(function(d) {
			layer.msg("服务器无响应");

		});
    	//编辑的Tree
    	$.ajax({
    		type : "GET",
    		dataType : "json",
    		url : "/getAllTreeData"
    			//,data : "pids="+ vals
    			//,beforeSend : beginWait("研判报告导出中，请稍稍后。。。")
    			//,complete : clearWait()
    	})
    	.done(function(data) {
    		$.fn.zTree.init($("#treeEdit"), setting, data);	
    		
    	})
    	.fail(function(d) {
    		layer.msg("服务器无响应");
    		
    	});
    	
    };
    return {
        init: function () {
        	//alert(AUTHORITY.includes("PERMISSION_ROLE"));
            initTable();
//            event();
//            formValid();
//            initZtree();
        }
    };

}();